/*
 * @Description: 
 * @Version: 1.0
 * @Autor: lairensi
 * @Date: 2021-08-31 11:47:09
 * @LastEditors: lairensi
 * @LastEditTime: 2021-08-31 13:53:15
 */
import 'package:flutter/material.dart';
import 'package:flutter_demo/api/user_service.dart';
import 'package:flutter_demo/config/main_shared_preferences_key.dart';
import 'package:flutter_demo/provider/user_provider.dart';
import 'package:flutter_demo/util/global.dart';
import 'package:flutter_demo/widget/gradient_button.dart';
import 'package:flutter_demo/widget/loading.dart';
import 'package:flutter_demo/widget/toast_msg.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:provider/provider.dart';

class LoginPage extends StatefulWidget {
  LoginPage({Key key}) : super(key: key);

  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  TextEditingController userName = TextEditingController();
  TextEditingController passWord = TextEditingController();

  @override
  initState() {
    _initStateAsync();
    super.initState();
   
  }

  // 初始化
  _initStateAsync() async {
    // 自动填充上次登录的用户名，填充后将焦点定位到密码输入框
    SharedPreferences prefs = await SharedPreferences.getInstance();
    print("登录");
    userName.text =
        prefs.getString(MainSharedPreferencesKey.UserName.toString());
    passWord.text =
        prefs.getString(MainSharedPreferencesKey.PassWord.toString());
    
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Container(
          margin: EdgeInsets.only(top: (200 / 2).w),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            children: <Widget>[
              Container(
                  margin: EdgeInsets.only(bottom: (100 / 2).h),
                  width: (275 / 2).w,
                  // height: (173 / 2).h,
                  child: Image(
                    image: AssetImage("lib/assets/images/logo275-173.png"),
                  )
              ),
              ConstrainedBox(
                constraints: BoxConstraints(
                    maxHeight: (64 / 2).w, maxWidth: (462 / 2).w),
                child: TextField(
                  controller: userName,
                  keyboardType: TextInputType.emailAddress,
                  decoration: InputDecoration(
                    contentPadding: EdgeInsets.all(0),
                    border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(100),
                        borderSide: BorderSide.none),
                    hintText: "请输入账号",
                    filled: true,
                    fillColor: Color.fromRGBO(255, 255, 255, 0.05),
                    prefixIcon: Icon(
                      Icons.perm_identity,
                      size: 18.w,
                      color: Color.fromRGBO(102, 102, 102, 1),
                    ),
                  ),
                  style: TextStyle(
                      textBaseline: TextBaseline.alphabetic,
                      fontSize: 12.sp,
                      color: Color.fromRGBO(153, 153, 153, 1)),
                  cursorColor: Color.fromRGBO(0, 158, 100, 1),
                ),
              ),
              Padding(
                padding: EdgeInsets.fromLTRB((144 / 2).w, 16.w, (144 / 2).w, 0),
                child: ConstrainedBox(
                  constraints: BoxConstraints(
                      maxHeight: (64 / 2).w, maxWidth: (462 / 2).w),
                  child: TextField(
                    controller: passWord,
                    obscureText: true,
                    decoration: InputDecoration(
                      contentPadding: EdgeInsets.all(0),
                      border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(100),
                          borderSide: BorderSide.none),
                      hintText: "请输入密码",
                      filled: true,
                      fillColor: Color.fromRGBO(255, 255, 255, 0.05),
                      prefixIcon: Icon(
                        Icons.lock,
                        size: 18.w,
                        color: Color.fromRGBO(102, 102, 102, 1),
                      ),
                    ),
                    style: TextStyle(
                        textBaseline: TextBaseline.alphabetic,
                        fontSize: 12.sp,
                        color: Color.fromRGBO(153, 153, 153, 1)),
                    cursorColor: Color.fromRGBO(0, 158, 100, 1),
                  ),
                ),
              ),
              GradientButton(
                text: "登录",
                top: (64 / 2).h,
                onTap: () => btnLogin(context),
              ),
            ],
          ),
        ),
        resizeToAvoidBottomPadding: false);
  }

  /// 登录
  void btnLogin(context) async {
    // 验证未输入值
    if (userName.text == '' || passWord.text == '') {
      ToastMsg().showToastMsg(
        msg: "请先输入用户账号及密码",
      );
      return;
    }

    var userInfoProvider = Provider.of<UserInfoProvider>(context, listen: false);

    Loading _loading = new Loading();
    _loading.showLoading(context, '正在登录中');
    var params = {"u": userName.text, "p": passWord.text};
    var tokenRes = await UserService.userLogin(params).then((res) {
      return res;
    });
    if (tokenRes["access_token"] == null) {
      ToastMsg().showToastMsg(
        msg: "用户名或密码错误,请您重新输入",
      );
      _loading.closeLoading(context);
      return;
    }
    String token = tokenRes['access_token'];

    // 更新TOKEN
    Global.TOKEN = token;

    // 在这里获取用户基本信息
    var userRes = await UserService.getUserinfo({});
    var userInfo = userRes["body"];

    // 更新provider userinfo
    userInfoProvider.changeUserName(userInfo);

    // 判断用户是否有权限进入系统
    var hasOpsRole = await UserService.hasOpsRole({"userId": userInfo["pid"]});

    if (!hasOpsRole["body"]) {
      ToastMsg().showToastMsg(
        msg: "您没有登录权限,请联系管理人员进行授权",
      );
      _loading.closeLoading(context);
      return;
    }

    _loading.closeLoading(context);
    ToastMsg().showToastMsg(
      msg: "登录成功",
    );

    // set缓存
    setSharedPreferences(userName.text, passWord.text, token.toString());

    // 转到首页
    Navigator.pushReplacementNamed(context, "/");
  }

   // 存储缓存
  void setSharedPreferences(userName, passWord, token) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setString(MainSharedPreferencesKey.UserName.toString(), userName);
    prefs.setString(MainSharedPreferencesKey.PassWord.toString(), passWord);
    prefs.setString(MainSharedPreferencesKey.Token.toString(), token);
  }
}
